package com.knowledge.plus.多线程.锁.显示锁;

import java.util.concurrent.locks.StampedLock;

/**
 * 邮戳锁，Java 8+
 * 特性：支持乐观读、三种模式（写/读/乐观读），性能更高。
 *
 * @author TPF
 * @since 2025/6/9
 */
public class StampedLockDemo {

    private double x, y;
    private final StampedLock sl = new StampedLock();

    // 写操作
    public void move(double deltaX, double deltaY) {
        long stamp = sl.writeLock(); // 获取写锁
        try {
            x += deltaX;
            y += deltaY;
        } finally {
            sl.unlockWrite(stamp);
        }
    }

    // 乐观读操作
    public double distanceFromOrigin() {
        long stamp = sl.tryOptimisticRead(); // 尝试乐观读
        double currentX = x, currentY = y;
        if (!sl.validate(stamp)) {          // 检查是否发生写操作
            stamp = sl.readLock();          // 升级为悲观读锁
            try {
                currentX = x;
                currentY = y;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return Math.sqrt(currentX * currentX + currentY * currentY);
    }

}
